'use strict';
const _ = require('../../libs/_');
const COL = global.db.collection('user');

module.exports = class User {
  constructor(info) {
    let self = this;

    _.extend(info, self);
  }

  save() {
    let self = this;
    console.log(123, self);
    return new Promise((resolve, reject) => {
      mongo.findOne(COL, {
        query: {
          openid: self.openid
        }
      }).then(doc => {
        if (doc) return resolve(doc);

        mongo.insertOne(COL, self).then(result => {
          self._id = result.insertedId;
          resolve(self);
        }).catch(reject);
      }).catch(reject);
    });
  }

  static find(_id) {
    return mongo.findOneByObjectId(COL, _id);
  }
};
